package XiaoNei::Utils;

use strict;
use Digest::MD5;
use URI;
use URI::QueryParam;


my @param_name_list = qw/
    user
    session_key
    expires
    in_canvas
    in_iframe
    profile
    time
    friends
    added
    profile_update_time
    api_key
    sms
    message
    sms_sid
    sms_new_user
    position_fix
/;



sub parse_param {
    my $rh_param = shift;
    my $rh_xn_param = {};
    my @param;
    for my $name (@param_name_list) {
       if (exists $rh_param->{'xn_sig_' . $name}) {
            $rh_xn_param->{$name} = $rh_param->{'xn_sig_' . $name};
            push @param, 'xn_sig_' . $name . '=' . $rh_param->{'xn_sig_' . $name};
       }
    }
    my $str = join '&', @param;
    return ($rh_xn_param, $str);
}

sub parse_param_from_str {
    my $sessionstr = shift;
    my $u = URI->new( '', 'http' );
    $u->query($sessionstr);

    my @param_name_list = $u->query_param;    
    my $rh_param = {};
    
    for my $name (@param_name_list) {
        $rh_param->{$name} = $u->query_param($name);
    }
    return parse_param($rh_param);
}
sub get_str_from_param {
    my $rh_param = shift;
    
    my $sessionstr = '';
    
    my @params;
    for my $name (keys %{$rh_param}) {
        push @params, "xn_sig_$name=" . $rh_param->{$name};
    }
    return join "&", @params;
}


sub gen_signature {
    my $rh_param = shift;
    my $secret = shift;
    my @params;
    for my $k (keys %$rh_param) {
        push @params, "$k=" . $rh_param->{$k}; 
    }
    @params = sort @params;
    my $str = (join '', @params) . ($secret || '');
    $str = Digest::MD5::md5_hex($str);
}


1;